package top.aicey.ai.sparring.processor;

import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.aicey.ai.sparring.common.holder.SparringContext;
import top.aicey.ai.sparring.configuration.RedisConfiguration;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 本地陪练上下文处理器
 * @author yangyongping
 * @date 2025-01-11 2:09 下午
 */
@Component
public class RedisSparringContextProcessor implements SparringContextProcessor {

    @Autowired
    private RedissonClient redissonClient;

    private final String REDIS_KEY = "sparring:context:%s";

    /**
     * 读取实例内容
     *
     * @param instanceId
     * @return
     */
    @Override
    public SparringContext get(String instanceId) {
        RBucket<SparringContext> bucket = redissonClient.getBucket(buildRedisKey(instanceId));
        return bucket.get();
    }

    /**
     * 设置上下文内容
     *
     * @param context
     * @return
     */
    @Override
    public void put(SparringContext context) {
        RBucket<SparringContext> bucket = redissonClient.getBucket(buildRedisKey(context.getInstanceId()));
        bucket.set(context);
    }

    /**
     * 清除上下文内容
     *
     * @param instanceId
     * @return
     */
    @Override
    public void clear(String instanceId) {
        RBucket<SparringContext> bucket = redissonClient.getBucket(buildRedisKey(instanceId));
        bucket.delete();
    }

    private String buildRedisKey(String instanceId){
        return String.format(REDIS_KEY,instanceId);
    }

}
